package com.biz.primus.ms.commodity.dao.specification;

import com.biz.primus.commodity.vo.BrandQueryVo;
import com.biz.primus.ms.commodity.dao.po.Brand;
import com.biz.primus.ms.commodity.dao.po.Category;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.util.List;

public class BrandSpecification implements Specification<Brand> {

    private BrandQueryVo reqVo;

    public BrandSpecification(BrandQueryVo brandQueryVo) {
        this.reqVo = brandQueryVo;
    }

    @Override
    public Predicate toPredicate(Root<Brand> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        List<Predicate> predicates = Lists.newArrayList();
        criteriaQuery.orderBy(criteriaBuilder.desc(root.get("createTimestamp")));
        if (reqVo.getCategoryId() != null) {
            ListJoin<Brand, Category> join = root.join(root.getModel().getList("categories", Category.class), JoinType.LEFT);
            predicates.add(criteriaBuilder.equal(join.get("id").as(Long.class), reqVo.getCategoryId()));
        }
        if (StringUtils.isNotBlank(reqVo.getName())) {
            Predicate predicate = criteriaBuilder.like(root.get("name").as(String.class), "%"+reqVo.getName()+"%");
            predicates.add(predicate);
        }
        criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
        return criteriaQuery.getRestriction();
    }
}
